<template>
	<view class="page-address">
		<uni-nav-bar :title="data.pageTitle" left-icon="left" :border="false"
			@clickLeft="proxy.$util.back"></uni-nav-bar>
		<view class="form">
			<uni-forms ref="form" validate-trigger="bind" :modelValue="data.form" :border="true" :rules="data.rules"
				label-width="120px">

				<uni-forms-item :label="$t('account.account.edit.currency')" name="currencie_id" required>
					<uni-data-select :placeholder="t('common.please_select')" v-model="data.form.currencie_id"
						:localdata="data.currencies"></uni-data-select>
				</uni-forms-item>


				<uni-forms-item :label="$t('account.account.edit.address')" name="address" required>
					<uni-easyinput :inputBorder="false" :clearable="false" type="text" v-model="data.form.address"
						:placeholder="getPlaceholder('address')" />
				</uni-forms-item>
				<uni-forms-item :label="$t('account.account.edit.qr_code')" name="qr_code" required>
					<view class="avatar-wrap" @click="changeAvatar">
						<image :src="data.form.qr_code" class="avatar-img" mode="aspectFit" />
					</view>
				</uni-forms-item>
			</uni-forms>
		</view>

		<view class="submit-wrap">
			<view @click="submit" class="btn-primary">{{ $t('common.btn_submit') }}</view>
		</view>
	</view>
</template>

<script setup>
	import {
		computed
	} from "vue";
	const {
		proxy
	} = getCurrentInstance()
	import {
		t
	} from '@/locale/index'
	import {
		requestHeader
	} from '@/common/util'
	import config from '@/config.js'
	import {
		onLoad
	} from "@dcloudio/uni-app";

	let id = 0;


	const getPlaceholder = (key) => {
		let length = key.split('.').length;
		let text = t(`account.account.edit.${key}`);
		if (length > 1) {
			text = t(key);
		}
		return t('common.please_enter') + text;
	};

	const data = reactive({
		form: {
			id: "",
			currencie_id: "",
			qr_code: "",
			address: "",
		},
		pageTitle: computed(() => {
			return data.form.id ? t('account.account.edit.heading_title') : t(
				'account.account.add_account')
		}),
		currencies: computed(() => {
			let data = uni.getStorageSync('settings').currencies;
			let lang = uni.getStorageSync("user_language");
			data = data.map(item => {
				return {
					text: lang == 'en' ? item.code : item.name,
					value: item.id
				}
			})

			return data;
		}),
		rules: {
			currencie_id: {
				rules: [{
					required: true,
					errorMessage: getPlaceholder("currency"),
					trigger: 'blur'
				}]
			},
			address: {
				rules: [{
					required: true,
					errorMessage: getPlaceholder('address'),
					trigger: 'blur'
				}]
			},
			qr_code: {
				rules: [{
					required: true,
					errorMessage: getPlaceholder('qr_code'),
					trigger: 'blur'
				}]
			},
		},
	})


	const changeAvatar = () => {
		const token = 'Authorization=Bearer ' + uni.getStorageSync('access-token');
		let baseUrl = config.apiBaseUrl

		// #ifdef H5
		baseUrl = 'api/'
		// #endif

		uni.chooseImage({
			count: 1,
			sizeType: ['original', 'compressed'],
			sourceType: ['album', 'camera'],
			crop: {
				width: uni.getSystemInfoSync().windowWidth,
				height: uni.getSystemInfoSync().windowWidth,
			},

			success(res) {
				const tempFilePaths = res.tempFilePaths

				uni.showLoading()
				uni.uploadFile({
					url: baseUrl + 'files?type=qrcode',
					header: {
						'Authorization': 'Bearer ' + uni.getStorageSync('access-token'),
						'accept': 'application/json',
					},
					filePath: tempFilePaths[0],
					name: 'file',
					success(res) {
						const item = JSON.parse(res.data)
						data.form.qr_code = item.data.url
					},
					fail(res) {
						// uni.showToast({ title: self.t('upload') })
					},
					complete() {
						uni.hideLoading()
					},
				})
			},
		})
	}

	const getAccountById = (id) => {
		proxy.$http.get(`customer_account/${id}`, ).then(res => {
			// console.log(res, "获取账号详情");
			data.form = res.data;
		})
	};

	const submit = () => {
		proxy.$refs.form.validate().then(() => {
			let url =  data.form.id ? `customer_account/${data.form.id}` :`customer_account`;
			let method = data.form.id ? 'put' : 'post'
			proxy.$http[method](url, data.form).then(res => {
				// console.log(res, "提交1");
				proxy.$util.msg(res.message, proxy.$util.back);
			})
		});
	}

	onLoad((option) => {
		data.form.id = option.id;
		if (option.id) getAccountById(option.id);
	});
</script>

<style lang="scss" scoped>
	@import url("@/pages/account/withdraw/withdraw.scss");
</style>